package com.lsy.weizhi2.customview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.lsy.weizhi2.R;
import com.lsy.weizhi2.myutils.AutoTextViewCall;
import com.lsy.weizhi2.utils.MyMethod;


/**
 * 自动垂直滚动的TextView
 */
public class AutoVerticalScrollTextView extends TextSwitcher implements ViewSwitcher.ViewFactory {

    private Context mContext;
    private SpannableStringBuilder[]infos;
    //mInUp,mOutUp分别构成向下翻页的进出动画
    private Rotate3dAnimation mInUp;
    private Rotate3dAnimation mOutUp;
    private int Time=5000;
    private AutoTextViewCall autoTextViewCall;
    private boolean isRotate;
    private int size;
    private Handler handler=new Handler();
    private Runnable rotateRunnable=new Runnable() {
        @Override
        public void run() {
            if(isRotate){
                next();
                handler.postDelayed(rotateRunnable,Time);
                //不要持有其他视图的静态常量
               /* if(HomeFragment2.isRunning){
                    handler.postDelayed(rotateRunnable,Time);
                }*/
            }
        }
    };
    public AutoVerticalScrollTextView(Context context) {
        this(context, null);
    }

    public AutoVerticalScrollTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.AutoTextView);
        size=typedArray.getInt(R.styleable.AutoTextView_Size,16);
        typedArray.recycle();
        init();

    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

    }

    public void setTextSize(int size){
        this.size=size;
    }
    private void init() {

        setFactory(this);

        mInUp = createAnim(true, true);
        mOutUp = createAnim(false, true);

        setInAnimation(mInUp);//当View显示时动画资源ID
        setOutAnimation(mOutUp);//当View隐藏是动画资源ID。
        mInUp.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                index++;
                setText(infos[(index)%infos.length]);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mOutUp.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                autoTextViewCall.ImageChange(AutoVerticalScrollTextView.this,index%infos.length);
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private Rotate3dAnimation createAnim( boolean turnIn, boolean turnUp){

        Rotate3dAnimation rotation = new Rotate3dAnimation(turnIn, turnUp);
        rotation.setDuration(Time);//执行动画的时间
        rotation.setFillAfter(true);//是否保持动画完毕之后的状态
        rotation.setInterpolator(new LinearInterpolator());//设置加速模式
        rotation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        return rotation;
    }


    //这里返回的TextView，就是我们看到的View,可以设置自己想要的效果
    public View makeView() {

        TextView textView = new TextView(mContext);
        textView.setGravity(Gravity.LEFT);
        textView.setTextSize(size);
        textView.setSingleLine(true);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(infos!=null&&infos.length!=0){
                    autoTextViewCall.onClick(view,(index)%infos.length);
                }
            }
        });
        //textView.setEllipsize(TextUtils.TruncateAt.END);
        return textView;

    }

    //定义动作，向上滚动翻页
    public void next(){
        //显示动画
        if(getInAnimation() != mInUp){
            setInAnimation(mInUp);
        }
        //隐藏动画
        if(getOutAnimation() != mOutUp){
            setOutAnimation(mOutUp);
        }
    }

    class Rotate3dAnimation extends Animation {
        private float mCenterX;
        private float mCenterY;
        private final boolean mTurnIn;
        private final boolean mTurnUp;
        private Camera mCamera;

        public Rotate3dAnimation(boolean turnIn, boolean turnUp) {
            mTurnIn = turnIn;
            mTurnUp = turnUp;
        }

        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            mCamera = new Camera();
            mCenterY = getHeight() ;
            mCenterX = getWidth() ;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

            final float centerX = mCenterX ;
            final float centerY = mCenterY ;
            final Camera camera = mCamera;
            final int derection = mTurnUp ? 1: -1;

            final Matrix matrix = t.getMatrix();

            camera.save();
            if (mTurnIn) {
                camera.translate(0.0f, derection *mCenterY * (interpolatedTime - 1.0f), 0.0f);
            } else {
                camera.translate(0.0f, derection *mCenterY * (interpolatedTime), 0.0f);
            }
            camera.getMatrix(matrix);
            camera.restore();

            matrix.preTranslate(-centerX, -centerY);
            matrix.postTranslate(centerX, centerY);
        }
    }

    /**
     * 设定字符串数组
     * @param infos 需要轮播的字符串
     */
    public void setStrings(SpannableStringBuilder[] infos){
        this.infos=infos;
    }

    /**
     * 设定轮播间隔时间
     * @param Time 毫秒
     */
    public void setTime(int Time){
        this.Time=Time;
    }
    int index=0;
    public int getIndex(){
       return index;
    }
    public int getCount(){
        return infos.length;
    }

    /**
     * 开始轮播
     */
    public void startRotate(){
        if(infos!=null){
            isRotate=true;
            Log.i("AutoText","info==="+infos[(index)%infos.length]);
            Log.i("AutoText","length==="+infos.length);

            setText(infos[(index)%infos.length]);
            index++;
            handler.postDelayed(rotateRunnable,Time);
        }
    }

    /**
     * 停止轮播
     */
    public void stopRotate(){
        isRotate=false;
    }
    /**
     * 设定回调
     * @param autoTextViewCall 回调接口
     */
    public void setAutoTextViewCall(AutoTextViewCall autoTextViewCall){
        this.autoTextViewCall=autoTextViewCall;
    }

}
